package utils

import (
	"XiangMu/models"
	"crypto/md5"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	uuid "github.com/satori/go.uuid"
	"os"
	"os/exec"
	"time"
)

func GetMd5(s string) string {

	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}
func GetUUID() string {
	return uuid.NewV4().String()
}

// 用户信息
type UserClaims struct {
	jwt.StandardClaims
	Account string `json:"account"`
	Id      int    `json:"identity"`
	Auth    int    `json:"auth"`
}

// Auth :0-学生，1-支部，2-党委
var MyKey = []byte("Dang")

// GenerateToken
// 生成token
func GenerateToken(id int, account string, auth int) (string, error) {
	expireToken := time.Now().Add(time.Hour * 24 * 7).Unix()
	userClaims := &UserClaims{
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireToken,
		},
		Account: account,
		Id:      id,
		Auth:    auth,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaims)
	s, err := token.SignedString(MyKey)
	if err != nil {
		return "", err
	}
	return s, nil
}

// TestAnalyseToken
// 解析token
func AnalyseToken(tokenString string) (*UserClaims, error) {
	userClaim := new(UserClaims)
	claims, err := jwt.ParseWithClaims(tokenString, userClaim, func(token *jwt.Token) (interface{}, error) {
		return MyKey, nil
	})
	if err != nil {
		return nil, err
	}
	if !claims.Valid {
		return nil, fmt.Errorf("invalid token:%v", err)
	}
	return userClaim, nil
}

type LabelValue struct {
	Label string `json:"label"`
	Value string `json:"value"`
}
type LabelCon struct {
	Label   string `json:"label"`
	Content string `json:"content"`
}

func formatBirthday(birthday string) string {
	t, err := time.Parse(time.RFC3339, birthday)
	if err != nil {
		return ""
	}
	return t.Format("2006年 1月2日")
}

func ConvertUserToLabelValue(user models.UserStatus) []LabelValue {
	return []LabelValue{
		{Label: "头像", Value: user.Avatar},
		{Label: "姓名", Value: user.Name},
		{Label: "性别", Value: map[int]string{0: "男", 1: "女"}[user.Sex]},
		{Label: "民族", Value: user.Nation},
		{Label: "出生年月日", Value: formatBirthday(user.Birthday)},
		{Label: "籍贯", Value: user.Origin},
		{Label: "身份证号码", Value: user.IdentityId},
		{Label: "单位、职务或职业", Value: user.Occupation},
		{Label: "学历 学位", Value: user.Education},
		{Label: "联系电话", Value: user.Phone},
		{Label: "家庭详细住址", Value: user.Address},
	}
}
func formatDate(input string) string {
	t, _ := time.Parse("2006-01-02", input)
	formatted := t.Format("2006年1月2日")
	return formatted
}
func ConvertDocxToPDF(inputFile string) error {
	//Linux/macOS 使用 soffice
	cmd := exec.Command(
		"libreoffice",
		"--headless",
		"--convert-to", "pdf",
		inputFile,
		"--outdir", ".",
	)
	//cmd := exec.Command(
	//	"C:/Program Files/LibreOffice/program/soffice.exe",
	//	"--headless",
	//	"--convert-to", "pdf",
	//	"--outdir", ".",
	//	inputFile,
	//)

	return cmd.Run()
}
func DelFile(inputFile string) {
	if _, err := os.Stat(inputFile); os.IsNotExist(err) {
		fmt.Println("文件不存在")
	} else {
		err = os.Remove(inputFile)
		if err != nil {
			fmt.Println("删除失败:", err)
		}
	}
}
